package com.example.roam.ui.activity;

import static com.zhihu.matisse.internal.utils.PathUtils.getDataColumn;
import static com.zhihu.matisse.internal.utils.PathUtils.isDownloadsDocument;
import static com.zhihu.matisse.internal.utils.PathUtils.isMediaDocument;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

import android.annotation.SuppressLint;
import android.content.ContentUris;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.net.Uri;
import android.os.Bundle;
import android.provider.DocumentsContract;
import android.provider.MediaStore;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.example.roam.R;
import com.example.roam.api.Api;
import com.example.roam.api.HttpUpload;
import com.example.roam.model.gson.InformationHead;
import com.example.roam.model.gson.User;
import com.example.roam.utils.Constans;
import com.example.roam.utils.HttpUtil;
import com.example.roam.utils.StatusBarUtils;
import com.google.android.material.imageview.ShapeableImageView;
import com.zhihu.matisse.Matisse;
import com.zhihu.matisse.MimeType;
import com.zhihu.matisse.engine.impl.GlideEngine;

import org.jetbrains.annotations.NotNull;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;

import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;
import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

public class UpdateInformationActivity extends AppCompatActivity {

    private TextView txt_username;
    private ShapeableImageView img_head;
    private EditText edt_username,edt_password;
    private RelativeLayout re_chc,re_spirit,re_head;
    private Button btn_confirm;
    private static final String TAG = "UpdateInformationActivity";
    private static final int REQUEST_CODE_CHOOSE = 100;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_update_information);
        StatusBarUtils.setWindowStatusBarColor(this, R.color.purple_500);//设置状态栏颜色为银白色

        initView();
        initData();
        initEvent();
    }

    public void initView(){
        txt_username = findViewById(R.id.txt_username);
        img_head = findViewById(R.id.img_head);
        edt_username = findViewById(R.id.edt_username);
        edt_password = findViewById(R.id.edt_password);
        re_chc = findViewById(R.id.re_chc);
        re_spirit = findViewById(R.id.re_spirit);
        re_head = findViewById(R.id.re_head);
        btn_confirm = findViewById(R.id.btn_confirm);
    }

    public void initData(){
        txt_username.setText(Constans.u_username);
        Glide.with(this).load(Constans.u_head).into(img_head);
        edt_username.setHint(Constans.u_username);
        edt_password.setHint("**********");
    }

    public void initEvent(){
        re_chc.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Log.i("TAG", "onClick: chc");
            }
        });

        re_spirit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Log.i("TAG", "onClick: spirit");
            }
        });

        re_head.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Log.i("TAG", "onClick: head");
                Matisse.from(UpdateInformationActivity.this) //Activity
                        .choose(MimeType.ofAll())//选择全部（包括视频）
                        .countable(true)  // 有序选择图片
                        .maxSelectable(1)  //最大选择数量为9
                        .gridExpectedSize(400)  //图片显示表格的大小
                        .restrictOrientation(ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED)
                        .thumbnailScale(0.85f)  //缩放比率
                        .theme(R.style.Matisse_Zhihu) //主题  暗色主题 R.style.Matisse_Dracula
                        .imageEngine(new GlideEngine()) //加载方式
                        .forResult(REQUEST_CODE_CHOOSE); //结果返回码 ，在onActivityResult中获取
            }
        });


        btn_confirm.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                postImage(filePath);
                retrofit = new Retrofit.Builder().baseUrl(HttpUtil.ADDRESS).build();
                retrofit.create(Api.class).updateUser(Constans.u_id,edt_username.getText().toString(),Constans.u_password,Constans.u_character,Constans.u_spirit,Constans.u_head,Constans.character_select,Constans.spirit_select,Constans.head_select,HttpUtil.COOKIE).enqueue(new Callback<ResponseBody>() {
                    @Override
                    public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {

                    }

                    @Override
                    public void onFailure(Call<ResponseBody> call, Throwable t) {

                    }
                });
            }
        });
    }

    private Retrofit retrofit;

    public void postImage(String realFilePath){
        File file = new File(realFilePath);
        RequestBody requestBody = RequestBody.create(MediaType.parse("image/jpeg"),file);
        MultipartBody.Part part = MultipartBody.Part.createFormData("uploadFile",file.getName(),requestBody);
        Retrofit retrofit = new Retrofit.Builder().addConverterFactory(GsonConverterFactory.create()).baseUrl(HttpUtil.FILE_ADDRESS).build();
        retrofit.create(HttpUpload.class).uploadUserHeadImg(part).enqueue(new Callback<InformationHead>() {
            @Override
            public void onResponse(Call<InformationHead> call, Response<InformationHead> response) {
                String url = response.body().getData().getUrl();
                UpdateInformationActivity.this.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Glide.with(UpdateInformationActivity.this).load(url).into(img_head);
                        Constans.u_head = url;
                    }
                });
            }
            @Override
            public void onFailure(Call<InformationHead> call, Throwable t) {

            }
        });
    }

    private ArrayList<Uri> mSelected;
    private String filePath;

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_CODE_CHOOSE && resultCode == RESULT_OK) {
            mSelected = (ArrayList<Uri>) Matisse.obtainResult(data);
            // 获取content的内容，使用environment加入获取bitmap。附加到
            if (mSelected.size() == 1) {
                Uri uri = mSelected.get(0);
                filePath = getRealPathFromUriAboveApi19(UpdateInformationActivity.this, uri);
            }
        }
    }

    @SuppressLint("NewApi")
    private static String getRealPathFromUriAboveApi19(Context context, Uri uri) {
        String filePath = null;
        if (DocumentsContract.isDocumentUri(context, uri)) {
            // 如果是document类型的 uri, 则通过document id来进行处理
            String documentId = DocumentsContract.getDocumentId(uri);
            if (isMediaDocument(uri)) { // MediaProvider
                // 使用':'分割
                String id = documentId.split(":")[1];
                String selection = MediaStore.Images.Media._ID + "=?";
                String[] selectionArgs = {id};
                filePath = getDataColumn(context, MediaStore.Images.Media.EXTERNAL_CONTENT_URI, selection, selectionArgs);
            } else if (isDownloadsDocument(uri)) { // DownloadsProvider
                Uri contentUri = ContentUris.withAppendedId(Uri.parse("content://downloads/public_downloads"), Long.valueOf(documentId));
                filePath = getDataColumn(context, contentUri, null, null);
            }
        } else if ("content".equalsIgnoreCase(uri.getScheme())) {
            // 如果是 content 类型的 Uri
            filePath = getDataColumn(context, uri, null, null);
        } else if ("file".equals(uri.getScheme())) {
            // 如果是 file 类型的 Uri,直接获取图片对应的路径
            filePath = uri.getPath();
        }
        return filePath;
    }
}